import { defineStore } from 'pinia'

import server from '@/config/server/index.js'

let api = {
  ad: server.api().get('/api/v1/ad/selectAll'),
  count: server.api().post('/api/v1/ad/addCount')
}

export const adStore = defineStore('ad', {
  state: () => {
    return {
      hasShow: false,
      ad: null
    }
  },
  actions: {
    show() {
      if (!this.hasShow) {
        return api.ad.fetch({ state: 1 }).then((res) => {
          this.hasShow = true
          if (res.length && res[0].imageUrl?.length) {
            this.ad = res[0]
            let url = JSON.parse(res[0].imageUrl)[0]?.url
            return url
          }
          return null
        })
      } else {
        return Promise.resolve()
      }
    },
    count() {
      api.count.fetch({ id: this.ad.id })
    }
  }
})
